#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;

int tickets = 10000; //假定有1w张票
pthread_mutex_t mutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP; //互斥锁（全局互斥锁可以直接用宏初始化）

//抢票功能实现
void* threadRoutine(void* args)
{
    string thread_nmae = static_cast<const char*>(args);
    while(true)
    {
        //加锁
        pthread_mutex_lock(&mutex);
        //表示还有票
        if(tickets > 0)
        {
            cout << thread_nmae << " : "<< tickets-- << endl;
            pthread_mutex_unlock(&mutex);
        }
        //没票了直接退出
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
        //充当抢完票后的动作
        usleep(1000);
    }
    return nullptr;
}

int main()
{
    pthread_t thread_id[5]; //存放每个线程的地址

    //创建线程
    for(int i = 0; i < 5; ++i)
    {
        char *buff = new char[64];
        snprintf(buff,64,"thread %d",i+1);
        pthread_create(thread_id+i,nullptr,threadRoutine,buff);
    }

    //释放线程
    for(int i = 0; i < 5; ++i)
    {
        pthread_join(thread_id[i],nullptr);
    }

    return 0;
}